<?php
class MD_Module
{
   public static function getAll()
   {
        return CMS_Db::getInstance()->fetchAll("SELECT * FROM module");
    }
    
    public static function categoryHasPermision($id_category, $controller)
    {
    	$sql = "select * from module m
    			inner join category_has_permisions c on (m.id = c.id_module ) 
    			where c.id_category = $id_category and m.system_name = '$controller' ";
    	$result = CMS_Db::getInstance()->fetchAll($sql);
    	
    	if ( count($result) > 0)
    		return true;
    	else
    		return false;	
    }
    
    public static function getModulesByCategory( $id)
    {
	   	return CMS_Db::getInstance()->fetchAll("SELECT id_module FROM category_has_permisions where id_category = $id ");
    }
    
    public static function getModuleDataByCategory($id)
    {
    	return CMS_Db::getInstance()->fetchAll("SELECT m.* FROM module m inner join  category_has_permisions c on ( c.id_module = m.id ) where c.id_category = $id ");
    }
    
    public static function getActualRootModule($controller)
	{
		$sql = "select m2.* from module m 
				inner join module m2 on ( m.id_module = m2.id )
				where m.system_name = '$controller'";
		return CMS_Db::getInstance()->fetchAll($sql);
	}
    
	public static function getSubModules( $module, $category )
	{
		$sql = "select m.* from module m
				inner join category_has_permisions c on ( m.id = c.id_module ) 
				where m.id_module = $module and c.id_category = $category ";	
		return CMS_Db::getInstance()->fetchAll($sql);
	}
	
    public static function getRootModules($id)
    {
    	$sql = "select m.* from module m 
    			where m.id_module = 0 and  ( 
    							select count(*) from module m2
								inner join category_has_permisions c 
								on ( m2.id = c.id_module ) 
								where m2.id_module = m.id 
								and c.id_category = $id ) > 0
    			group by m.id  ";
    	
    	return CMS_Db::getInstance()->fetchAll($sql);
    }
    
    
    public static function updatePermisions($categories, $id)
    {
    	CMS_Db::getInstance()->delete('category_has_permisions', "id_category = $id" );
    	
    	foreach( $categories as $c )
    	{
    		CMS_Db::getInstance()->insert('category_has_permisions', array( 'id_module' => $c, 'id_category' => $id ));
    	}
    }
    
}